package org.zjx.db;

import org.zjx.common.bean.Transfer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TransferDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public TransferDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Transfer
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS transfer (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    type INTEGER NOT NULL,\n"
                + "    screenId INTEGER NOT NULL,\n"
                + "    location TEXT NOT NULL,\n"
                + "    clickPoint TEXT,\n"
                + "    targetScreenId INTEGER,\n"
                + "    targetLocation TEXT NOT NULL,\n"
                + "    dialogues TEXT\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert a Transfer record
    public void insert(Transfer transfer) {
        String sql = "INSERT INTO transfer(type, screenId, location, clickPoint, targetScreenId, targetLocation, dialogues) VALUES(?, ?, ?, ?, ?, ?, ?)";
        Object[] params = {
                transfer.getType(),
                transfer.getScreenId(),
                transfer.getLocation(),
                transfer.getClickPoint(),
                transfer.getTargetScreenId(),
                transfer.getTargetLocation(),
                transfer.getDialogues()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update a Transfer record
    public void update(Transfer transfer) {
        String sql = "UPDATE transfer SET type = ?, screenId = ?, location = ?, clickPoint = ?, targetScreenId = ?, targetLocation = ?, dialogues = ? WHERE id = ?";
        Object[] params = {
                transfer.getType(),
                transfer.getScreenId(),
                transfer.getLocation(),
                transfer.getClickPoint(),
                transfer.getTargetScreenId(),
                transfer.getTargetLocation(),
                transfer.getDialogues(),
                transfer.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete a Transfer record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM transfer WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Transfer by ID
    public Transfer findById(int id) {
        String sql = "SELECT * FROM transfer WHERE id = ?";
        Object[] params = {id};
        List<Transfer> transfers = dbHelper.executeQuery(sql, params, Transfer.class);
        if (transfers.isEmpty()) return null;
        return transfers.get(0);
    }

    // Find Transfer by Screen ID
    public List<Transfer> findByScreenId(int screenId) {
        String sql = "SELECT * FROM transfer WHERE screenId = ?";
        Object[] params = {screenId};
        return dbHelper.executeQuery(sql, params, Transfer.class);
    }

    // Get all Transfers
    public List<Transfer> findAll() {
        String sql = "SELECT * FROM transfer";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Transfer.class);
    }

    // Paginated query for Transfers
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM transfer LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Transfer> transfers = dbHelper.executeQuery(sql, params, Transfer.class);

        String countSql = "SELECT COUNT(*) FROM transfer";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("transferList", transfers);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Transfer data
    public void clearData() {
        dbHelper.clearData("transfer");
    }

    // Drop the Transfer table
    public void dropTable() {
        dbHelper.dropTable("transfer");
    }
}
